<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Jobs\OrderDeliverJob;
use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $input = $request->input();
        $search = ['user_id' => '', 'title' => '', 'user.nickname' => '', 'start_at' => '', 'end_at' => '', 'status' => ''];
        $list = Order::with('product_snapshot')
            ->with('address_snapshot')
            ->withCertain('user', ['nickname', 'avatar_url'])->apply($search, $input)->orderBy("id", "desc")
            ->paginate(per_page());
        return $this->paginate($list);
    }

    /**
     * 填写快递单号
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function delivery(Request $request) {
        $this->validate($request, [
            'express_title' => 'required',
            'express_sn' => 'required',
            'id' => 'required',
        ]);
        $input = $request->input();
        $order = Order::find($input['id']);
        if (!$order)
            return $this->failed('订单不存在');

        if ($order->status == Order::STATUS_DELIVER_DONE)
            return $this->failed('订单状态异常');

        $input['status'] = Order::STATUS_DELIVER_DONE;
        $order->update($input);

        $this->dispatch(new OrderDeliverJob($input['id']));
        return $this->success([]);
    }

}

